<?php

if (!defined('ABSPATH')) {
    exit();
}
class CMC_Shortcode
{

/*
|--------------------------------------------------------------------------
| Bootstraping CMC main list
|--------------------------------------------------------------------------
 */
    public function __construct()
    {
        add_action('wp_enqueue_scripts', array($this, 'cmc_register_scripts'));

        add_shortcode('global-coin-market-cap', array($this, 'cmc_global_data'));
        //add_action('init',array($this,'cmc_save_api_data'));
        add_shortcode('coin-market-cap', array($this, 'cmc_shortcode'));
        add_shortcode('cmc-technical-analysis', array($this, 'cmc_technical_analysis'));

        add_action('wp_ajax_dt_get_coins_list', array($this, 'cmc_dt_get_coins_list'));
        add_action('wp_ajax_nopriv_dt_get_coins_list', array($this, 'cmc_dt_get_coins_list'));

        add_action('wp_ajax_cmc_ajax_search', array($this, 'cmc_ajax_search'));
        add_action('wp_ajax_nopriv_cmc_ajax_search', array($this, 'cmc_ajax_search'));

        // if (cmc_isMobileDevice() == 0) {
        //     add_action('wp_ajax_cmc_small_charts', array($this, 'cmc_small_chart_data'));
        //     add_action('wp_ajax_nopriv_cmc_small_charts', array($this, 'cmc_small_chart_data'));
        // }
        // Apply RTl css
        add_action('init', array($this, 'cmc_rtl_check'));

    }

    public function cmc_rtl_check()
    {
        global $wp_locale;
        $check = $wp_locale->is_rtl();
        if ($check == true) {
            wp_enqueue_style('cmc_rtl_css', CMC_URL . 'assets/css/cmc-rtl.css', null, CMC);
        }
    }

    public function cmc_save_api_data()
    {
        // run only if transient does not exists
        if (false === ($cache = get_transient('cmc-saved-data'))) {
            cmc_check_cache();
        }
    }
/*
|--------------------------------------------------------------------------
| CMC list server side processing ajax callback
|--------------------------------------------------------------------------
 */
    public function cmc_dt_get_coins_list()
    {

        require CMC_PATH . 'includes/helpers/cmc-serverside-processing.php';
        get_ajax_data();
        wp_die();
    }

/*
|-----------------------------------------------------------------|
|    Shortcode for Technical Analysis  widget                      |
|-----------------------------------------------------------------|
 */
    public function cmc_technical_analysis($atts, $content = null)
    {
        global $post;
        $atts = shortcode_atts(array(
            'autosize' => 'false',
            'interval' => '1m',
            'width' => '425',
            'height' => '450',
            'theme' => 'light',
            'interval-tabs' => 'true',
            'locale' => 'en',
            'transparent' => 'true',
        ), $atts, 'cmc');

        $availabel_coins = array("BTC", "ETH", "USDT", "XRP", "BNB", "USDC", "STETH", "ADA", "DOGE", "SOL", "TRX", "LTC", "MATIC", "DOT", "BCH", "WBTC", "SHIB", "AVAX", "TON", "UNI", "XLM", "LINK", "DAI", "BUSD", "LEO", "XMR", "TUSD", "ETC", "ATOM", "OKB", "FIL", "ICP", "LDO", "HBAR", "CRO", "QNT", "VET", "NEAR", "AAVE", "MKR", "GRT", "OP", "FRAX", "SNX", "IMX", "ALGO", "EGLD", "SAND", "EOS", "XDC", "AXS", "THETA", "XTZ", "USDD", "APE", "KAS", "MANA", "FTM", "BSV", "RNDR", "INJ", "BGB", "CRV", "NEO", "FLOW", "GT", "GALA", "KAVA", "RPL", "XRD", "XEC", "KCS", "PEPE", "USDP", "CHZ", "GMX", "KLAY", "COMP", "PAXG", "XAUT", "MIOTA", "LUNC", "FXS", "CSPR", "BTT", "HT", "MINA", "SUI", "TWT", "AR", "NEXO", "DASH", "GUSD", "CFX", "WOO", "ZIL", "DYDX", "CAKE", "1INCH", "BONE", "GNO", "ENJ", "OSMO", "FLR", "LUSD", "BAT", "CVX", "MASK", "LRC", "RUNE", "AGIX", "MX", "QTUM", "TFUEL", "XEM", "XCH", "ROSE", "ZEC", "BLUR", "CELO", "BTG", "ENS", "ASTR", "ILV", "GMT", "DFI", "YFI", "HOT", "BDX", "FET", "TOMI", "FLOKI", "DCR", "HNT", "AZERO", "RVN", "JST", "ICX", "CVXCRV", "KSM", "ANKR", "JASMY", "LUNA", "GLM", "SXP", "FNSA", "WEMIX", "AUDIO", "WAVES", "UNIBOT", "BAL", "ETHW", "BABYDOGE", "SC", "IOTX", "WAXP", "RON", "ANT", "ONT", "IOST", "MAGIC", "GLMR", "SFP", "MSOL", "USTC", "OCEAN", "BAND", "RBN", "ONE", "BORA", "AXL", "BRISE", "DAO", "ZEN", "EURS", "KDA", "BICO", "KNC", "ORDI", "GNS", "AKT", "WBETH", "HIVE", "DGB", "TRIBE", "ELF", "TOMO", "SKL", "SSV", "SUSHI", "LSK", "EWT", "UMA", "CORE", "STG", "SYN", "CHSB", "POLY", "DAG", "LPT", "POLYX", "EDU", "ASTRAFER", "CTSI", "JOE", "LYXE", "BLD", "LQTY", "CFG");

        $symbol = null == get_query_var('coin_symbol') ? 'BTC' : strtoupper(sanitize_text_field(get_query_var('coin_symbol')));
        $interval = !empty($atts['interval']) ? $atts['interval'] : '1m';
        $autosize = !empty($atts['autosize']) ? $atts['autosize'] : 'true';
        $transparent_bg = !empty($atts['transparent']) ? $atts['transparent'] : 'true';
        $width = !empty($atts['width']) ? $atts['width'] : '425';
        $height = !empty($atts['height']) ? $atts['height'] : '450';
        $theme = !empty($atts['theme']) ? $atts['theme'] : 'light';
        $locale = !empty($atts['locale']) ? $atts['locale'] : 'en';
        $interval_tab = !empty($atts['interval-tabs']) ? $atts['interval-tabs'] : 'true';
        $apply_autosize = '';
        if ($autosize == 'true') {
            $width = '100%';
            $height = '100%';
            $apply_autosize = 'autosize';
        }

        $html = '<!---------- CMC Version:-' . CMC . ' By Cool Plugins Team-------------->';
        $html .= '<!-- TradingView Widget BEGIN -->
	<div class="tradingview-widget-container ' . esc_attr($apply_autosize) . '" id="ccpw-analysis-widget-' . esc_attr($post->ID) . '">';

        if (in_array($symbol, $availabel_coins)) {
            $html .= '<div class="tradingview-widget-container__widget"></div>
	    <div class="tradingview-widget-copyright"><a href="https://www.tradingview.com/symbols/' . esc_attr($symbol) . 'USD/technicals/" rel="noopener" target="_blank"><span class="blue-text">Technical Analysis for ' . esc_html($symbol) . 'USD</span></a> by TradingView</div>
	  <script type="text/javascript" src="https://s3.tradingview.com/external-embedding/embed-widget-technical-analysis.js" async>
	  {
	  "showIntervalTabs": ' . esc_js($interval_tab) . ',
	  "width": "' . esc_js($width) . '",
	  "colorTheme": "' . esc_js($theme) . '",
	  "isTransparent": ' . esc_js($transparent_bg) . ',
	  "locale": "' . esc_js($locale) . '",
	  "symbol": "CRYPTO:' . esc_js($symbol) . 'USD",
	  "interval": "' . esc_js($interval) . '",
	  "height": "' . esc_js($height) . '"
	}
	  </script>';
        } else {
            $html .= '<div class="cmc_no_response">' . __('No technical data available for this coin') . '</div>';
        }

        $html .= '</div>
	<!-- TradingView Widget END -->';

        return $html;
    }

/*
|--------------------------------------------------------------------------
| CMC list main shortcode for coin market cap table.
|--------------------------------------------------------------------------
 */
    public function cmc_shortcode($atts, $content = null)
    {
            $atts = shortcode_atts(array(
            'id' => '',
            'class' => '',
            'info' => true,
            'paging' => false,
            'scrollx' => true,
            'ordering' => true,
            'searching' => false,
        ), $atts, 'cmc');

        // Ensure the 'id' is an integer to prevent script injection
        $post_id = intval($atts['id']);
        
        $status = get_post_status($post_id) == "publish";
        $get_license = get_option('cmc_license_registration');

        $purchased_code = isset($get_license["cmc-purchase-code"]) ? $get_license["cmc-purchase-code"] : '';
  
        $notice = '';
        // Do not proceed further if
        if (empty($purchased_code)) {
            $notice = __('<b>Please enter and activate your license key for Coins MarketCap plugin for unrestricted and full access of all premium features.</b><br>', 'cmc');
        }
        if (!cmc_check_required_settings()) {
            if ($notice) {
                return $notice;
            }
            $api_option = get_option("openexchange-api-settings");

            $api_type = (isset($api_option['select_api'])) ? $api_option['select_api'] : "coingecko";

            if ($api_type == "coingecko") {
                return __('Please enter Coingecko Free Api Key to get this plugin works', 'cmc');

            } else if ($api_type == "coinmarketcap") {
                return __('Please enter CoinMarketcap  Api Key to get this plugin works', 'cmc');

            } else if ($api_type == "both_coingecko" || $api_type == "both_coinmarketcap") {
                return __('Please enter Coingecko & CoinMarketcap Api Key to get this plugin works', 'cmc');

            }

        }

        if ($status == false) {
            return sprintf(__('Shortcode with id %d is not available', 'cmc'), $post_id);
        }

        // Don't run any database update if transient is saved (even if expired)
        if (false == get_option('cmc-coin-initialization', false)) {
            //$api_obj = new CMC_api_data();

            $rs = CMC_api_data::cmc_get_selected_api_data();
            
            if ($rs) {
                update_option('cmc-coin-initialization', date("Y-m-d h:m A"));
            }
        }

        $total_found = 1830;
        $start_at = 0;
        $start_point = 0;
        $data_length = 10;
        $db = new CMC_Coins;
        $cmc_link_array = array();
        $post_id = intval($atts['id']); // Ensure post_id is an integer to prevent script injection
        
        // Initialize Titan
        $live_updates = '';
        $live_updates = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_live_updates', true));
        
        $binance_url = get_post_meta($post_id, 'cmc_binance_url', true);
        $this->cmc_load_assets($live_updates,$binance_url);
        $show_coins = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_show_currencies', true));
        $get_category = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_cmc_select_category', true));
        $load_coins_react = intval(sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_load_currencies', true)));
        $show_category = !empty($get_category) ? $get_category : "all";
        $load_coins = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_load_currencies', true));
        $hide_next_priv = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_hide_next_priv', true));
        $real_currency = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_old_currency', true));
        $settings_table_type = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_settings_table_type', true));
        $search_placeholder = __("Search", "cmc");
        $old_currency = $real_currency ? $real_currency : "USD";
        // Prediction Settings Fetch Here
        $show_predi = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_prediction', true));
        $predi_up_low = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_pred_up_down', true));
        $pred_per = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_pred_perce', true));
        // Prediction Fetch Settings End Here
        // for currency dropdown
        //$api_obj=new CMC_api_data();
        $api_option = get_option("openexchange-api-settings");
        $cache_time = !empty($api_option['select_cache_time']) ? intval($api_option['select_cache_time']) : 15;
        
        $currencies_price_list = CMC_api_data::cmc_usd_conversions('all');
        $selected_currency_rate = CMC_api_data::cmc_usd_conversions($old_currency);
        $currency_symbol = cmc_old_cur_symbol($old_currency);

        $single_default_currency = cmc_get_option('default_currency');
        $pagination = $show_coins ? $show_coins : 50;

        $display_supply = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_display_supply', true));
        $display_Volume_24h = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_display_Volume_24h', true));
        $display_24h_changes = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_display_24h_changes', true));
        $display_7d_changes = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_display_7d_changes', true));
        $display_30d_changes = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_display_30d_changes', true));
        $display_1y_changes = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_display_1y_changes', true));
        $display_market_cap = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_display_market_cap', true));
        $display_chart = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_coin_price_chart', true));
        $cmc_small_charts = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_cmc_chart_type', true));
        $enable_datatable_search = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_enable_datatable_search', true));
        $enable_datatable_search = empty($enable_datatable_search) ? 'false' : 'true';
        $display_ath = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_display_ath', true));
        $display_high_24h = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_display_high_24h', true));
        $display_low_24h = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_display_low_24h', true));
        $ath_change_percentage = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_ath_change_percentage', true));
        $ath_date = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_ath_date', true));
        $api_type = (isset($api_option['select_api'])) ? $api_option['select_api'] : "coingecko";

        $live_updates_cls = '';

        if ($live_updates) {
            $live_updates_cls = 'cmc_live_updates';
            update_option('live-stream-on-single', 'enable');
        } else {
            $live_updates_cls = '';
            update_option('live-stream-on-single', 'disable');
        }
        $enable_formatting = (get_post_meta($post_id, 'cmc_single_settings_enable_formatting', true)) ? true : false;
        $single_page_type = get_post_meta($post_id, 'cmc_single_settings_single_page_type', true);
        $link_in_newtab = $single_page_type ? true : 0;
        $single_page_slug = cmc_get_page_slug();
        $cmc_data_attributes = '';
        //    $cmc_data_attributes .= 'data-pageLength="' . $pagination . '"';
        $cmc_coins_page = (get_query_var('page') ? get_query_var('page') : 1);
        $default_logo = (string) CMC_URL . 'assets/coins-logos/default-logo.png';
        $bitcoin_price = cmc_btc_price();
        $c_json = currencies_json();
        $arr=array();
        $unique_number = wp_unique_id('cmc_');

$arr[$unique_number] = [
    'showCategory' => $show_category,
    'showCoins' => $show_coins,
    'realCurrency' => $real_currency,
    'loadCoins' => $load_coins_react,
    'hideNextPriv' => $hide_next_priv,
    'oldCurrency' => $old_currency,
    'selectedCurrencyRate' => $selected_currency_rate,
    'currencySymbol' => $currency_symbol,
    'pagination' => $pagination,
    'displaySupply' => $display_supply,
    'displayVolume24h' => $display_Volume_24h,
    'display24hChanges' => $display_24h_changes,
    'display7dChanges' => $display_7d_changes,
    'display30dChanges' => $display_30d_changes,
    'display1yChanges' => $display_1y_changes,
    'displayMarketCap' => $display_market_cap,
    'displayChart' => $display_chart,
    'enableDatatableSearch' => $enable_datatable_search,
    'displayAth' => $display_ath,
    'displayHigh24h' => $display_high_24h,
    'displayLow24h' => $display_low_24h,
    'athChangePercentage' => $ath_change_percentage,
    'athDate' => $ath_date,
    'enableFormatting' => $enable_formatting,
    'singlePageType' => $single_page_type,
    'linkInNewTab' => $link_in_newtab,
    'singlePageSlug' => $single_page_slug,
    'defaultLogo' => $default_logo,
    'liveUpdates' => $live_updates,
    'singlePageType' => $single_page_type,
    'cacheTime' => $cache_time,
    'apiType'=>$api_type
];

wp_localize_script('cmc-main-table', 'cmcTableSettings_' . $unique_number, array(
    'data' => $arr[$unique_number],
));



        if ($show_category != 'all') {
            $cmcDB = new CMC_Coins;
            $coins_list_ids = array();
            $coindata = $cmcDB->get_coins(array("coin_category" => $show_category));
            if ($coindata) {

                foreach ($coindata as $coin) {
                    $coins_list_ids[] = $coin->coin_id;
                   
                }
                cmc_update_ua_coins_on_save_post($coins_list_ids, $show_category);
            }
        }
        $api_option = get_option("openexchange-api-settings");

        $api_type = (isset($api_option['select_api'])) ? $api_option['select_api'] : "coingecko";


        $coins_db = new CMC_Coins();
        $total_coins = $coins_db->get_total_coins_count(); // Get the total coins count

        if (!isset($settings_table_type) || empty($settings_table_type)) {
            $settings_table_type = 'php';
        }
       
       if($settings_table_type == 'php' ){
       
        $html = '';
        $html .= '<!---------- CMC Version:-' . CMC . ' By Cool Plugins Team-------------->';
    
        $html .= '<div id="cryptocurency-market-cap-wrapper" data-default-logo="' . esc_attr($default_logo) . '" >';

        $html .= '<script id="cmc_curr_list" type="application/json">' . esc_attr($c_json) . '</script>';

        if ($hide_next_priv == true) {
            $cmc_prev_coins = __('Previous', 'cmc');
            $cmc_next_coins = __('Next', 'cmc');
            $styles = "<style>#cmc_coinslist_wrapper .top, #cmc_coinslist_wrapper .bottom {
		display: none;
	}</style>";
        } else {
            $cmc_prev_coins = __('Previous', 'cmc');
            $cmc_next_coins = __('Next', 'cmc');
            $styles = '';
        }
        $coin_loading_lbl = __('Loading...', 'cmc');
        $cmc_no_data = __('No Coin Found', 'cmc');
        $cmc_no_fav_data = __('No Favourite Coin', 'cmc');

        $coin_url = home_url($single_page_slug, '/');
        if ($old_currency == $single_default_currency) {
            $url_type = "default";
        } else {
            $url_type = "custom";
        }
//    $html.='<div class="top-scroll-wrapper"><div class="top-scroll"></div></div>';
        //Pass data-prediper && data-predi value in table attr.
        $html .= '<div class="cmc-filter-wrap ' . ($enable_datatable_search == "true" ? 'in_search' : '') . '">';
        $html .= '<div class="cmc-fav cmc_icon-star-empty" id="cmc_toggel_fav" title="' . __('Show/Hide Watch List', 'cmc') . '"></div>';

        $html .= '<div class="cmc-currency-search-wrap"><div class="cmc_price_conversion">
<select id="cmc_usd_conversion_box" class="cmc_conversions">';
        $currencies_price_list['BTC'] = !empty($bitcoin_price) ? $bitcoin_price : '';
        foreach ($currencies_price_list as $name => $price) {
            $csymbol = cmc_old_cur_symbol($name);
            if ($name == $old_currency) {

                $html .= '<option selected="selected" data-currency-symbol="' . esc_attr($csymbol) . '" data-currency-rate="' . esc_attr($price) . '"  value="' . esc_attr($name) . '" >' . esc_html($name) . '</option>';
            } else {
                $html .= '<option data-currency-symbol="' . esc_attr($csymbol) . '" data-currency-rate="' . esc_attr($price) . '"  value="' . esc_attr($name) . '">' . esc_html($name) . '</option>';
            }
        }
        unset($currencies_price_list['BTC']);
        $html .= '</select></div>';
        if ($enable_datatable_search == "false" && ($hide_next_priv == " " || $hide_next_priv == false)) {
            $html .= coin_search($old_currency, $single_default_currency, $single_page_slug);
        }
        $html .= '</div></div>';
        $html .= '<table id="cmc_coinslist"  data-datatable-search="' . esc_attr($enable_datatable_search) . '" data-search-label="' . esc_attr($search_placeholder) . '" data-loadinglbl="' . esc_attr($coin_loading_lbl) . '" data-number-formating="' . esc_attr($enable_formatting) . '" data-pagination="' . esc_attr($pagination) . '" data-total-coins="' . esc_attr($load_coins) . '" data-currency-symbol="' . esc_attr($currency_symbol) . '"
	data-prev-coins="' . esc_attr($cmc_prev_coins) . '" data-zero-fav-records="' . esc_attr($cmc_no_fav_data) . '" data-zero-records="' . esc_attr($cmc_no_data) . '" data-next-coins="' . esc_attr($cmc_next_coins) . '"
	data-currency-rate="' . esc_attr($selected_currency_rate) . '" data-old-currency="' . esc_attr($old_currency) . '" data-category="' . esc_attr($show_category) . '" class="' . esc_attr($live_updates_cls) . '  cmc-datatable table table-striped table-bordered cmc-table-loader 
	width="100%" data-showpredi="' . esc_attr($show_predi) . '"  data-predi="' . esc_attr($predi_up_low) . '" data-prediper="' . esc_attr($pred_per) . '" data-post_id = "' . esc_attr($post_id) . '"data-watch-title="' . __('Add to watch list', 'cmc') . '" data-unwatch-title="' . __('Remove from watch list', 'cmc') . '"
    >';
        $preloader_url = CMC_URL . 'images/chart-loading.svg';
        $html .= '<thead data-preloader="' . esc_attr($preloader_url) . '">
		<tr>
		<th data-classes="cmc-rank" data-index="rank" class="desktop">' . __('#', 'cmc') . '</th>
		<th data-link-in-newtab="' . esc_attr($link_in_newtab) . '" data-single-url="' . esc_attr($coin_url) . '" data-url-type="' . esc_attr($url_type) . '"  data-classes="cmc-name" data-index="name" class="all">' . __('Name', 'cmc') . '</th>';
        $html .= '<th data-classes="cmc-price"  data-index="price" class="all">' . __('Price', 'cmc') . '</th>';
        if (has_action('cmc_rating_column')) {
            ob_start();
            do_action('cmc_rating_column', $post_id);
            $action_output = ob_get_contents();
            ob_end_clean();
            $html .= $action_output;
        }
        if (has_action('cmc_risco_column')) {
            ob_start();
            do_action('cmc_risco_column', $post_id);
            $action_output = ob_get_contents();
            ob_end_clean();
            $html .= $action_output;
        }

        if ($display_24h_changes == 1 || $display_24h_changes == "on") {
            $html .= '<th data-classes="cmc-live-ch cmc-changes 24h-live-changes" data-index="percent_change_24h">' . __('Changes ', 'cmc') . ' <span class="badge  badge-default">' . __('24H ', 'cmc') . '</span></th>';
        }
        if ($display_7d_changes == 1 || $display_7d_changes == "on") {
            $html .= '<th data-classes=" cmc-changes" data-index="percent_change_7d">' . __('Changes ', 'cmc') . ' <span class="badge  badge-default">' . __('7D ', 'cmc') . '</span></th>';
        }
        if ($display_30d_changes == 1 || $display_30d_changes == "on") {
            $html .= '<th data-classes=" cmc-changes" data-index="percent_change_30d">' . __('Changes ', 'cmc') . ' <span class="badge  badge-default">' . __('30D ', 'cmc') . '</span></th>';
        }
        if (($display_1y_changes == 1 || $display_1y_changes == "on") && ($api_type == "coingecko" || $api_type == "both_coingecko")) {
            $html .= '<th data-classes=" cmc-changes" data-index="percent_change_1y">' . __('Changes ', 'cmc') . ' <span class="badge  badge-default">' . __('1Y ', 'cmc') . '</span></th>';
        }
        if ($display_high_24h == 1 || $display_high_24h == "on") {
            $html .= '<th data-classes="cmc-high" data-index="high_24h">' . __('High', 'cmc') . ' ' . '<span class="badge  badge-default">' . __('24H', 'cmc') . '</th>';
        }
        if ($display_low_24h == 1 || $display_low_24h == "on") {
            $html .= '<th data-classes="cmc-low" data-index="low_24h">' . __('Low', 'cmc') . ' ' . '<span class="badge  badge-default">' . __('24H', 'cmc') . '</th>';
        }
        // Prediction Column Start Here
        if (has_action('cmc_prediction_column')) {
            ob_start();
            do_action('cmc_prediction_column', $post_id);
            $action_output = ob_get_contents();
            ob_end_clean();
            $html .= $action_output;
        }

        // Prediction Column End Here
        if ($display_market_cap == 1 || $display_market_cap == "on") {
            $html .= '<th data-classes="cmc-market-cap" data-sort-default data-index="market_cap">' . __('Market Cap', 'cmc') . '</th>';
        }
        if ($display_Volume_24h == 1 || $display_Volume_24h == "on") {
            $html .= '<th data-classes="cmc-vol" data-index="volume">' . __('Volume ', 'cmc') . '<span class="badge  badge-default">' . __('24H', 'cmc') . '</span></th>';
        }
        if (has_action('cmc_audido_column')) {
            ob_start();
            do_action('cmc_audido_column', $post_id);
            $action_output = ob_get_contents();
            ob_end_clean();
            $html .= $action_output;
        }
        if ($display_supply == 1 || $display_supply == "on") {
            $html .= '<th data-classes="cmc-supply"  data-index="supply">' . __('Available Supply', 'cmc') . '</th>';
        }
        if (($display_ath == 1 || $display_ath == "on") && ($api_type == "coingecko" || $api_type == "both_coingecko")) {
            $html .= '<th data-classes="cmc-ath" data-index="ath">' . __('ATH', 'cmc') . '</th>';
        }
        if (($ath_change_percentage == 1 || $ath_change_percentage == "on") && ($api_type == "coingecko" || $api_type == "both_coingecko")) {
            $html .= '<th data-classes="cmc-ath-chnage-per" data-index="ath_change_percentage">' . __('ATH', 'cmc') . '<span class="badge  badge-default">' . __('% Change', 'cmc') . '</th>';
        }
        if (($ath_date == 1 || $ath_date == "on") && ($api_type == "coingecko" || $api_type == "both_coingecko")) {
            $html .= '<th data-classes="cmc-ath-date" data-index="ath_date">' . __('ATH  ', 'cmc') . '<span class="badge  badge-default">' . __('Date', 'cmc') . '</th>';
        }

        if ($display_chart == 1 || $display_chart == "on") {
            $period = '7d';
            $points = 0;
            if ($old_currency == "USD") {
                $currency_price = 1;
            } else {
                $currency_price = $selected_currency_rate;
            }
            $no_data_lbl = __('No Graphical Data', 'cmc');
            $chart_fill = "true";

            $html .= '<th data-sort-method="none" id="cmc_weekly_charts_head" data-classes="cmc-charts"  data-index="weekly_chart"  data-orderable="false"
			data-msz="' . esc_attr($no_data_lbl) . '"
			data-period="' . esc_attr($period) . '"
			data-points="' . esc_attr($points) . '"
			data-currency-symbol="' . esc_attr($currency_symbol) . '"
			data-currency-price="' . esc_attr($currency_price) . '"
			data-chart-fill="' . esc_attr($chart_fill) . '"
		>'
            . __('Price Graph ', 'cmc') . __('<span class="badge badge-default">(7D)</span>', 'cmc2') . '</th>';

        }

        $html .= '</tr></thead>
	<tbody></tbody><tfoot>
</tfoot></table></div>';

        if ($styles != '') {
            ob_start();
            echo $styles;
            $styles = ob_get_contents();
            ob_end_clean();
            return $notice . $html . $styles;
        } else {
            return $notice . $html;
        }
    }
    else{
        
        wp_enqueue_style('cmc-main-table-style');
        return '<div id="cmc_chart_table_' . $unique_number . '" cmc-unique-number="' . $unique_number . '"><div class="cmc_chart_table"></div></div>';
    }
    }

/*
|--------------------------------------------------------------------------
| CMC Global Info shortcode handler
|--------------------------------------------------------------------------
 */
    public function cmc_global_data($atts, $content = null)
    {

        $atts = shortcode_atts(array(
            'id' => '',
            'currency' => 'USD',
            'formatted' => true,
            'type'=> 'classic'
        ), $atts);
        
        wp_register_style('cmc-global-style', false);
        wp_enqueue_style('cmc-global-style');
        $post_id = intval($atts['id']);
        $settings_table_type = sanitize_text_field(get_post_meta($post_id, 'cmc_single_settings_settings_table_type', true));
        
        $wrapper_class = ($atts['type'] == 'classic') ? 'cmc_classic' : 'cmc_modern';

        $cmc_g_styles = ($atts['type'] == 'classic')
        ? '/* Global Market Cap Data */
        .cmc_classic .cmc_global_data {
            display:inline-block;
            margin-bottom:5px;
            width:100%;
        }
        .cmc_classic .cmc_global_data ul {
            list-style: none;
            margin: 0;
            padding: 0;
            display: inline-block;
            width: 100%;
        }
        .cmc_classic .cmc_global_data ul li {
            display: inline-block;
            margin-right: 20px;
            font-size:14px;
            margin-bottom: 5px;
        }
        .cmc_classic .cmc_global_data ul li .global_d_lbl {
            font-weight: bold;
            background: #f9f9f9;
            padding: 4px;
            color: #3c3c3c;
            border: 1px solid #e7e7e7;
            margin-right: 5px;
        }
        .cmc_classic .cmc_global_data ul li .global_data {
            font-size: 13px;
            white-space:nowrap;
            display:inline-block;
        }
        .cmc_classic .cmc_global_data ul li .global_d_lbl i {
            font-size: 1.25em;
            margin-top: -3px;
        }
        /* Global Market Cap Data END */'
        : '/* Global Market Cap Data */
        .cmc_modern .cmc_global_data {
            display: inline-block;
            margin-bottom: 5px;
            width: 100%;
        }
        .cmc_modern .cmc_global_data ul {
            list-style: none;
            margin: 0;
            padding: 0;
            display: flex;
            flex-wrap: wrap;
            margin-left: 10%;
            gap: 20px;
            justify-content: center;
        }
        .cmc_modern .cmc_global_data ul li {
            background:rgb(244, 244, 255);
            padding: 1rem;
            font-size: 1.3rem;
            border-radius: 15px;
            width: calc(25% - -25px);
            height: 110px;
            text-align: center;
            transition: transform 0.3s, box-shadow 0.3s;
        }
        /* Hover Effect */
        .cmc_modern .cmc_global_data ul li:hover {
            transform: translateY(-5px);
        }
        .cmc_modern .cmc_global_data ul li .global_d_lbl {
            font-weight: bold;
            color: #333333;
            font-size: 14px;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .cmc_modern .cmc_global_data ul li .global_d_lbl i {
            font-size: 1.5em;
            color:#514c4c;
            margin-right: 8px;
        }
        .cmc_modern .cmc_global_data ul li .global_data {
            font-size: 20px;
            font-weight: 600;
            color:rgb(0, 0, 0);
        }
        @media only screen and (max-width: 992px){
            .cmc_modern .cmc_global_data ul li .global_data {
                font-size: 14px;
                font-weight: 500;
            }
        }
        @media only screen and (max-width: 556px){
            .cmc_modern .cmc_global_data ul li {
                width: 100%;
            }
            .cmc_modern .cmc_global_data ul {
                margin-left: 0px;
            }
        }
        /* Global Market Cap Data END */';
    
        
        wp_add_inline_style('cmc-global-style', $cmc_g_styles);

        $output = '';
        //$api_obj=new CMC_api_data();
        $bitcoin_percentage_of_market_cap = '';
        $old_currency = $atts['currency'] ? $atts['currency'] : 'USD';
        $currency_symbol = cmc_old_cur_symbol($old_currency);
        $fiat_currency_rate = CMC_api_data::cmc_usd_conversions($old_currency);
        $global_data = (array) cmc_get_global_data();
        if (is_array($global_data) && count($global_data) > 0) {
            if (isset($global_data['market_cap_percentage']->btc)) {
                $bitcoin_percentage_of_market_cap = number_format($global_data['market_cap_percentage']->btc, '2', '.', '');
            }
            $output .= '<div class="' . $wrapper_class . '"><div class="cmc_global_data"><ul>';
            if (isset($global_data['total_market_cap']) && isset($global_data['total_volume'])) {
                if ($old_currency == "USD") {
                    $market_cap = $global_data['total_market_cap'];
                    $volume = $global_data['total_volume'];
                } else {
                    $market_cap = $global_data['total_market_cap'] * $fiat_currency_rate;
                    $volume = $global_data['total_volume'] * $fiat_currency_rate;
                }
            }

            if (isset($market_cap)) {
                if ($atts['formatted'] == "true") {
                    $mci_html = $currency_symbol . cmc_format_coin_values($market_cap);
                } else {
                    $mci_html = $currency_symbol . format_number($market_cap);
                }
                $output .= '<li style="display:inline-block;"><span class="global_d_lbl"><i class="cmc_icon-wallet"></i>' . __('Market Cap:', 'cmc') . '</span><span class="global_data"> ' . esc_html($mci_html) . '</span></li>';
            }

            if (isset($volume)) {
                if ($atts['formatted'] == "true") {
                    $vci_html = $currency_symbol . cmc_format_coin_values($volume);
                } else {
                    $vci_html = $currency_symbol . format_number($volume);
                }
                $output .= '<li style="display:inline-block;"><span class="global_d_lbl"><i class="cmc_icon-chart"></i>' 
                . ($atts['type'] == 'classic' ? __('24h Vol:', 'cmc') : __('Volume 24h', 'cmc'))
                . '</span><span class="global_data"> ' . esc_html($vci_html) . '</span></li>';
            }
            $output .= '<li style="display:inline-block;"><span class="global_d_lbl"><i class="cmc_icon-volume"></i>'
            . ($atts['type'] == 'classic' ? __('BTC Dominance: ', 'cmc') : __('BTC Dominance ', 'cmc'))
            . '</span><span class="global_data">' . esc_html($bitcoin_percentage_of_market_cap) . '%</span></li>';
            $output .= '</ul></div></div>';
        }
        return $output;
    }

/*
|--------------------------------------------------------------------------
|Register scripts and styles
|--------------------------------------------------------------------------
 */
    public function cmc_register_scripts()
    {
        if (!is_admin()) {

            if (!wp_script_is('jquery', 'done')) {
                wp_enqueue_script('jquery');
            }
            $api_option = get_option("openexchange-api-settings");

            $api_type = (isset($api_option['select_api'])) ? $api_option['select_api'] : "coingecko";
            wp_register_script('cmc-datatables', CMC_URL . 'assets/js/libs/jquery.dataTables.min.js', 'jquery', CMC);
            wp_register_script('cmc-main-table', CMC_URL . 'assets/main-table/build/index.js', array('wp-element', 'wp-components'), null, CMC, true);
            wp_register_script('bootstrapcdn', CMC_URL . 'assets/js/libs/bootstrap.min.js', null, CMC);
            wp_register_style('cmc-main-table-style', CMC_URL . 'assets/main-table/build/index.css', null, CMC);
            wp_register_script('cmc-table-sort', CMC_URL . 'assets/js/libs/tablesort.min.js', array('jquery'), CMC, true);
            wp_register_style('cmc-icons', CMC_URL . 'assets/css/cmc-icons.min.css', null, CMC);
            wp_register_style('cmc-custom', CMC_URL . 'assets/css/cmc-custom.css', null, CMC);
            wp_register_style('cmc-bootstrap', CMC_URL . 'assets/css/libs/bootstrap.min.css', null, CMC);
            wp_register_style('cmc-advance-table-design', CMC_URL . 'assets/css/cmc-advance-style.css', null, CMC);
            
            wp_register_script('crypto-numeral', CMC_URL . 'assets/js/libs/numeral.min.js', array('jquery'), CMC);
            wp_register_script('cmc-custom-fixed-col', CMC_URL . 'assets/js/libs/tableHeadFixer.js', array('jquery', 'cmc-datatables', 'cmc-table-sort'), CMC, true);
            wp_register_script('cmc-typeahead', CMC_URL . 'assets/js/libs/typeahead.bundle.min.js', array('jquery'), CMC, true);
            wp_register_script('ccpw-lscache', CMC_URL . 'assets/js/libs/lscache.min.js', array('jquery'), CMC, true);
            wp_register_script('cmc-js', CMC_URL . 'assets/js/cmc-main-table.js', array('jquery', 'cmc-datatables', 'cmc-table-sort'), CMC, true);
            wp_register_script('cmc-handlebars', CMC_URL . 'assets/js/libs/handlebars-v4.0.11.js', array('jquery'), CMC, true);
            wp_register_script('cmc-chartjs', CMC_URL . 'assets/js/libs/Chart.bundle.min.js', null, CMC);
            
            

            wp_register_script('cmc-small-charts', CMC_URL . 'assets/js/small-charts.js', array('jquery', 'cmc-chartjs'), CMC, true);
            wp_localize_script(
                'cmc-js',
                'data_object',
                array(
                    'ajax_url' => admin_url('admin-ajax.php'),
                    'nonce' => wp_create_nonce('wp_rest'),
                    'domain_url' => get_site_url(),
                    'api_type' => $api_type,
                    'cmc_plugin_url' => CMC_URL,
                    'localize_text' => array('B' => __(' B', 'cmc'), 'M' => __(' M', 'cmc'), 'K' => __(' K', 'cmc'), 'T' => __(' T', 'cmc')),
                    'api_url' => get_rest_url(null, "coin-market-cap/v1/table/main"),
                )
            );

            wp_localize_script('cmc-main-table', 'cmcMTGlobalData', array(
                'homeUrl' => site_url(),
                'nonce' => wp_create_nonce('wp_rest'),
                'searchUrl' => esc_url(rest_url('coin-market-cap/v1/search-coins')),
            ));

            $dynamic_css = cmc_dynamic_style();
            wp_add_inline_style('cmc-custom', $dynamic_css);

            //loading globally for fast rendering
            wp_enqueue_style('cmc-bootstrap');
            wp_enqueue_style('cmc-custom');
            wp_enqueue_style('cmc-icons');
            wp_enqueue_style('cmc-advance-table-design');
            // wp_enqueue_style('cmc-main-table-style');

        }
    }

/*
|--------------------------------------------------------------------------
| get plugin settings
|--------------------------------------------------------------------------
 */
    public function cmc_get_settings($post_id, $index)
    {
        if ($post_id && $index) {
            // Initialize Titan

            $val = get_post_meta($post_id, $index, true);
            if ($val) {
                return true;
            } else {
                return false;
            }
        }
    }

/*
|--------------------------------------------------------------------------
| Loading required assets for coin single page
|--------------------------------------------------------------------------
 */
    public function cmc_load_assets($live_updates,$binance_url)
    {

        //wp_enqueue_script('cmc-lscache');
        
        wp_enqueue_script('bootstrapcdn');
        wp_enqueue_script('crypto-numeral');

        wp_enqueue_script('cmc-typeahead');
        wp_enqueue_script('cmc-handlebars');
        wp_enqueue_script('cmc-chartjs');
        wp_enqueue_script('cmc-small-charts');

        wp_enqueue_script('cmc-custom-fixed-col');
        wp_enqueue_script('cmc-table-sort');
        //wp_enqueue_script('cmc-numeraljs');
        wp_enqueue_script('ccpw-lscache');
        wp_enqueue_script('cmc-js');
        wp_enqueue_script('cmc-main-table');

     
        if ($live_updates) {
            wp_enqueue_script('ccc-binance-socket', CMC_URL . 'assets/js/socket/binance.min.js', array('jquery'), CMC, true);
            wp_enqueue_script('ccc_stream', CMC_URL . 'assets/js/socket/cmc-stream.js', null, CMC, true);
            wp_localize_script('ccc_stream', 'cmc_settings', array('live_changes' => $live_updates,'binance_url' => $binance_url));

        }
    }

    public function cmc_ajax_search()
    {
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field($_POST['_wpnonce']) : (isset($_SERVER['HTTP_X_WP_NONCE']) ? sanitize_text_field($_SERVER['HTTP_X_WP_NONCE']) : '');

        if (!wp_verify_nonce($nonce, 'wp_rest')) {
            wp_send_json_error('Nonce verification failed');
            wp_die(); // Ensure the script stops executing if nonce verification fails
        }

        $all_coins = cmc_coin_list_data();

        if (is_array($all_coins) && count($all_coins) > 0) {
            $cmc_link_array = array();
            foreach ($all_coins as $id => $coin) {
                $coin_id = sanitize_text_field($id);
                $coin_symbol = sanitize_text_field($coin['symbol']);
                $name = sanitize_text_field($coin['name']);
                $cmc_link_array[] = array("id" => $coin_id, "name" => $name, "symbol" => $coin_symbol);
            }
            $search_links = json_encode($cmc_link_array, JSON_UNESCAPED_SLASHES);
            wp_send_json_success($search_links);
        } else {
            wp_send_json_error('No coins found');
        }
    }

}